package com.quxing.amazon.security;

import cn.hutool.core.util.StrUtil;
import com.quxing.amazon.common.BaseException;
import com.quxing.amazon.common.ResponseUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.quxing.amazon.common.StatusConst.*;

/**
 * @Author zhb
 * @Description 全局权限鉴权过滤
 * @Date 2020/11/27 16:55
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class JwtAuthorizationFilter extends OncePerRequestFilter {


    private final JwtUtil jwtUtil;

    private final JwtUserDetailsServiceImpl jwtUserDetailsServer;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String jwt = jwtUtil.getJwtFromRequest(request);
        if (StrUtil.isNotBlank(jwt)) {
            try {
                //解析token
                Claims claims = jwtUtil.parseJwt(jwt);
                UserDetails userDetails = jwtUserDetailsServer.loadUserByUsername(claims.getSubject());
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                //将token加入上下文中
                SecurityContextHolder.getContext().setAuthentication(authentication);
                filterChain.doFilter(request, response);
            } catch (JwtException e) {
                log.error("token解析失败:{}", e.getMessage());
                ResponseUtil.writeError(response, TOKEN_EXPIRE_CODE, TOKEN_EXPIRED);
            } catch (BaseException e) {
                log.error("token:{}", e.getMsg());
                ResponseUtil.writeError(response, TOKEN_EXPIRE_CODE, e.getMsg());
            } catch (Exception e) {
                log.error("未知异常:{}", e.getMessage());
                ResponseUtil.writeError(response, TOKEN_EXPIRE_CODE, ERROR);
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }

}
